<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <h2 class="login-brand">{{ $t('brand.lg') }}</h2>
        </div>
        <div class="login-body">
          <el-tabs v-model="activeName">
            <el-tab-pane label="手机号注册" name="sms">
              <el-form :model="mobileForm" :rules="mobileRule" ref="mobileForm"
                @keyup.enter.native="mobileFormSubmitHandle()" status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="mobile">
                  <el-input v-model="mobileForm.mobile" :placeholder="$t('login.mobile')">
                    <i slot="prefix" class="el-input__icon el-icon-phone-outline"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <el-col :span="10">
                    <el-input v-model="mobileForm.code" :placeholder="$t('login.validateCode')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-lock"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="7" :offset="7">
                    <el-button @click="getMobileCode()" :disabled="mobileFlag" class="w-percent-100" :loading="loading">
                      {{ mobileBtnTitle }}
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="mobileFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    注册
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="邮箱注册" name="email">
              <el-form :model="emailForm" :rules="emailRule" ref="emailForm"
                @keyup.enter.native="emailFormSubmitHandle()" status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="loginKey">
                  <el-input v-model="emailForm.email" :placeholder="$t('login.email')">
                    <i slot="prefix" class="el-input__icon el-icon-user"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="validateCode">
                  <el-col :span="10">
                    <el-input v-model="emailForm.code" :placeholder="$t('login.validateCode')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-lock"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="7" :offset="7">
                    <el-button @click="getEmailCode()" :disabled="emailFlag" class="w-percent-100" :loading="loading">
                      {{ emailBtnTitle }}
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="emailFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    注册
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-row>
              <el-link :underline="false" @click="gotoLoginView()">使用已有账户登录</el-link>
            </el-row>
          </el-tabs>
        </div>
        <div class="login-footer">
          <p>
            <a href="http://www.uniedp.cn/#/login" target="_blank">{{ $t('login.demo') }}</a>
          </p>
          <p><a href="http://www.uniedp.cn" target="_blank">{{ $t('login.copyright') }}</a>2019 © uniedp.cn</p>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import {
  validateMobile,
  validateEmail
} from '@/utils/validate'
export default {
  data () {
    return {
      activeName: 'sms',
      count: 60,
      timer: null,
      mobileFlag: false,
      emailFlag: false,
      mobileBtnTitle: this.$t('login.checkCodeBtn'),
      emailBtnTitle: this.$t('login.checkCodeBtn'),
      loading: false,
      i18nMessages: messages,
      captchaPath: '',
      dataForm: {
        username: '',
        password: '',
        uuid: '',
        captcha: ''
      },
      mobileForm: {
        mobile: '',
        code: null
      },
      emailForm: {
        email: '',
        code: null
      },
      isValidateCodeLogin: false
    }
  },
  computed: {
    mobileRule () {
      return {
        mobile: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    emailRule () {
      return {
        email: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {

  },
  methods: {
    gotoLoginView () {
      this.$router.replace({ name: 'login' })
    },
    // 获取手机验证码
    getMobileCode () {
      this.$refs.mobileForm.validateField('mobile', mobileError => {
        if (!mobileError) {
          const TIME_COUNT = 120
          // 发送手机验证码
          if (!this.timer) {
            this.count = TIME_COUNT
            this.mobileFlag = true
            // 验证手机号码是否正确
            this.sendSmsCode(this.mobileForm.mobile)
            this.mobileBtnTitle = '重新发送（' + this.count + '）'
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.mobileBtnTitle = '重新发送（' + this.count + '）'
              } else {
                this.mobileFlag = false
                clearInterval(this.timer)
                this.timer = null
                this.mobileBtnTitle = '重新发送'
              }
            }, 1000)
          }
        } else {
          return false
        }
      })
    },
    // 获取邮箱验证码
    getEmailCode () {
      this.$refs.emailForm.validateField('email', mobileError => {
        if (!mobileError) {
          const TIME_COUNT = 120
          // 发送手机验证码
          if (!this.timer) {
            this.count = TIME_COUNT
            this.emailFlag = true
            // 验证手机号码是否正确
            this.sendEmailCode(this.emailForm.email)
            this.emailBtnTitle = '重新发送（' + this.count + '）'
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.emailBtnTitle = '重新发送（' + this.count + '）'
              } else {
                this.emailFlag = false
                clearInterval(this.timer)
                this.timer = null
                this.emailBtnTitle = '重新发送'
              }
            }, 1000)
          }
        } else {
          return false
        }
      })
    },
    // 发送短信验证码
    sendSmsCode (loginKey) {
      this.$http.post(`/register/sendSmsCode`, { params: { mobile: loginKey } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
      })
    },
    // 发送邮件验证码
    sendEmailCode (loginKey) {
      this.$http.post(`/register/sendEmailCode`, { params: { mobile: loginKey } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
      })
    },
    // 手机验证码提交
    mobileFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.mobileForm.validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        this.$http.post('/register/mobile', this.mobileForm).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return false
          }
          this.$cookies.set('token', res.data)
          this.$router.replace({ name: 'home' })
        }).catch((err) => {
          this.loading = false
          console.error(err)
          this.$message.error('系统异常，请联系管理员')
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 邮箱验证码提交
    emailFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.emailForm.validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        this.$http.post('/register/email', this.emailForm).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return false
          }
          this.$cookies.set('token', res.data)
          this.$router.replace({ name: 'home' })
        }).catch((err) => {
          this.loading = false
          console.error(err)
          this.$message.error('系统异常，请联系管理员')
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
    // postLoginValidateCode (formData) {
    //   this.$http.post('/loginByValidateCode', formData).then(({ data: res }) => {
    //     if (res.code !== 0) {
    //       this.loading = false
    //       return false
    //     }
    //     console.log('login', this)
    //     if (this.returnUrl) {
    //       // 重定向
    //       let url = this.returnUrl
    //       url = URLUtil.urlConcat(url, 'token', res.data.token)
    //       location.href = url
    //     } else {
    //       this.$cookies.set('token', res.data.token)
    //       this.$router.replace({ name: 'home' })
    //     }
    //   }).catch((err) => {
    //     this.loading = false
    //     console.error(err)
    //     this.$message.error('系统异常，请联系管理员')
    //   })
    // }
  }
}
</script>
